from project.models import Project, ProjectRole, Participate
from technology.models import Use, Technology
from user.models import User
from technology.utils.list import list_technologies_by_project


def project_view(project):
    assert isinstance(project, Project)
    leader = project.leader
    # print(Participate.objects.filter(rid__in=ProjectRole.objects.filter(pid=project)))
    members = [p.uid for p in
               Participate.objects.filter(rid__pid=project).order_by('uid_id')]
    if len(members) > 0:
        top_designer = members[0]
        top_designer_view = {
            'called': Participate.objects.get(uid=top_designer, rid__pid=project).rid.name,
            'user': {
                'id': top_designer.id,
                'name': top_designer.name
            }
        }
    else:
        top_designer_view = None
    view = {
        'id': project.id,
        'name': project.name,
        'leader': {
            'id': leader.id,
            'name': leader.name
        },
        'current_version': project.current_version,
        'detail': project.detail,
        'start_time': {
            'year': project.start_time.year,
            'month': project.start_time.month,
            'day': project.start_time.day
        },
        'top_designer': top_designer_view,
        'members': [{
            'id': member.id,
            'name': member.name,
            'role': {
                'id': ProjectRole.objects.get(participate__uid=member, pid=project).id,
                'name': ProjectRole.objects.get(participate__uid=member, pid=project).name
            },
            'annotation': Participate.objects.get(uid=member,
                                                  rid__pid=project).annotation
        } for member in members],
        'technologies': [{
            'id': tech.id,
            'name': tech.name,
            'annotation': Use.objects.get(pid=project, tid=tech).annotation
        } for tech in list_technologies_by_project(project)]
    }
    return view


def member_view(project, user):
    assert isinstance(project, Project)
    assert isinstance(user, User)
    project_role = ProjectRole.objects.get(pid=project, participate__uid=user)
    view = {
        'id': user.id,
        'name': user.name,
        'role': {
            'id': project_role.id,
            'name': project_role.name
        },
        'annotation': Participate.objects.get(uid=user, rid__in=ProjectRole.objects.filter(pid=project)).annotation
    }
    return view


def technology_view(project, technology):
    assert isinstance(project, Project)
    assert isinstance(technology, Technology)
    use = Use.objects.get(pid=project, tid=technology)
    view = {
        'id': technology.id,
        'name': technology.name,
        'annotation': use.annotation
    }
    return view
